import { emitNewPlot } from "@/components/EventBus";

const ws = new WebSocket(`ws://${window.location.host}/api/echo`);   //建立websocket链接
//接收数据
ws.onopen = function () {
    console.log('open!')
    ws.send("aaaaaa")
}
type CallbackList = ((s: string) => void)[]
type MessageType = "subprocess-output" | "plot" | "message"
const _handlers: {
    "subprocess-output": CallbackList,
    "plot": CallbackList,
    "message": CallbackList
} = { "subprocess-output": [], plot: [], message: [] };

interface WSMessage {
    type: MessageType,
    payload: any
}
ws.onmessage = function (messageEvent) {
    // console.log("data", messageEvent.data)
    // emitNewPlot(JSON.parse(messageEvent.data))
    const data: WSMessage[] = JSON.parse(messageEvent.data)
    if (_handlers == null) {
        throw Error
    }
    if (data == null) {
        throw Error
    }
    for (const ws_msg of data) {
        const type = ws_msg.type as MessageType
        let handled = false
        for (const handler of _handlers[type]) {
            handler(ws_msg.payload)
            handled = true
        }
        if (!handled) {
            console.error("Unhandled event data:", messageEvent.data)
        }
    }
}

export const addOnMessageHandler = (type: MessageType, handler: (s: any) => void) => {

    _handlers[type].push(handler)
}
export { ws }